#include <stdio.h>
#include <unistd.h>
#include <pthread.h>

/* 读写锁 */
pthread_rwlock_t rwlock;
int num = 1;

void *read_1(void *arg)
{
    while (1) {
        pthread_rwlock_rdlock(&rwlock);
        printf("read num first===%d\n", num);
        pthread_rwlock_unlock(&rwlock);
        sleep(1);
    }
}

void *read_2(void *arg)
{
    while (1) {
        pthread_rwlock_rdlock(&rwlock);
        printf("read num second===%d\n", num);
        pthread_rwlock_unlock(&rwlock);
        sleep(2);
    }
}

void *write_1(void *arg)
{
    while (1) {
        pthread_rwlock_wrlock(&rwlock);
        num++;
        printf("write thread first\n");
        pthread_rwlock_unlock(&rwlock);
        sleep(1);
    }
}

void *write_2(void *arg)
{
    while (1) {
        pthread_rwlock_wrlock(&rwlock);
        num++;
        printf("write thread second\n");
        pthread_rwlock_unlock(&rwlock);
        sleep(1);
    }
}

int main(void)
{
    pthread_t ptd1, ptd2, ptd3, ptd4;

    pthread_rwlock_init(&rwlock, NULL);

    pthread_create(&ptd1, NULL, read_1, NULL);
    pthread_create(&ptd2, NULL, read_2, NULL);
    pthread_create(&ptd3, NULL, write_1, NULL);
    pthread_create(&ptd4, NULL, write_2, NULL);

    pthread_join(ptd1, NULL);
    pthread_join(ptd2, NULL);
    pthread_join(ptd3, NULL);
    pthread_join(ptd4, NULL);

    pthread_rwlock_destroy(&rwlock);

    return 0;
}